package servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import service.DAO;

import model.User;

import com.google.gson.Gson;

/**
 * Servlet implementation class FB
 */
@WebServlet("/FB")
public class FB extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FB() {
		super();

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */

	/*
	 * 
	 * private String printUserInfo(Long uid, FacebookXmlRestClient client,
	 * String sessionKey) throws FacebookException
	 * 
	 * 
	 * {
	 * 
	 * 
	 * StringBuffer ret = new StringBuffer();
	 * 
	 * 
	 * //init array parameter
	 * 
	 * 
	 * ArrayList<Long> uids = new ArrayList<Long>(1);
	 * 
	 * 
	 * uids.add(uid);
	 * 
	 * 
	 * //init field parameter - we choose all profile infos.
	 * 
	 * 
	 * List<ProfileField> fields = Arrays.asList(ProfileField.values());
	 * 
	 * 
	 * 
	 * 
	 * 
	 * //init the client in order to make the xml request
	 * 
	 * 
	 * client = new FacebookXmlRestClient(apiKey, secretKey, sessionKey);
	 * 
	 * 
	 * //get the xml document containing the infos
	 * 
	 * 
	 * Document userInfoDoc = client.users_getInfo(uids, fields);
	 * 
	 * 
	 * 
	 * 
	 * 
	 * //for each info append it to returned string buffer
	 * 
	 * 
	 * for (ProfileField pfield : fields)
	 * 
	 * 
	 * {
	 * 
	 * 
	 * ret.append(pfield.fieldName()).append(" <b>").append(userInfoDoc.
	 * getElementsByTagName(pfield.fieldName()).
	 * item(0).getTextContent()).append("</b>");
	 * 
	 * 
	 * ret.append("</br>");
	 * 
	 * 
	 * }
	 * 
	 * 
	 * return ret.toString();
	 * 
	 * 
	 * }
	 */
	/*
	 * String apiKey = "256662071116007"; String secretKey =
	 * "9c329e2cc15e5924654e21d31f683fef";
	 * 
	 * private String printUserInfo(Long uid, FacebookXmlRestClient client,
	 * String sessionKey) throws FacebookException
	 * 
	 * { StringBuffer ret = new StringBuffer(); ArrayList<Long> uids = new
	 * ArrayList<Long>(1); uids.add(uid);
	 * 
	 * // init field parameter - we choose all profile infos.
	 * 
	 * List<ProfileField> fields = Arrays.asList(ProfileField.values());
	 * 
	 * // init the client in order to make the xml request
	 * 
	 * client = new FacebookXmlRestClient(apiKey, secretKey, sessionKey);
	 * 
	 * // get the xml document containing the infos
	 * 
	 * Document userInfoDoc = client.users_getInfo(uids, fields);
	 * 
	 * // for each info append it to returned string buffer
	 * 
	 * for (ProfileField pfield : fields)
	 * 
	 * {
	 * 
	 * ret.append(pfield.fieldName()) .append(" <b>") .append(userInfoDoc
	 * .getElementsByTagName(pfield.fieldName()).item(0)
	 * .getTextContent()).append("</b>");
	 * 
	 * ret.append("</br>");
	 * 
	 * }
	 * 
	 * return ret.toString();
	 * 
	 * }
	 */
	@SuppressWarnings("deprecation")
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String YOUR_APP_ID = "256662071116007";
		// String YOUR_REDIRECT_URI1 =
		// "http://www.fiyatineydi.com/FN/facebook2.jsp";
		String YOUR_REDIRECT_URI1 = "http://www.fiyatineydi.com/FB";
		String SOME_ARBITRARY_BUT_UNIQUE_STRING = "123987456asdfsdf";
		//String COMMA_SEPARATED_LIST_OF_PERMISSION_NAMES = "";
		// String COMMA_SEPARATED_LIST_OF_PERMISSION_NAMES = "user_photos";
		String COMMA_SEPARATED_LIST_OF_PERMISSION_NAMES =
		 "friends_photos";
		String URL1 = "https://www.facebook.com/dialog/oauth?type=client_cred&client_id="
				+ YOUR_APP_ID
				+ "&redirect_uri="
				+ YOUR_REDIRECT_URI1
				+ "&scope="
				+ COMMA_SEPARATED_LIST_OF_PERMISSION_NAMES
				+ "&state=" + SOME_ARBITRARY_BUT_UNIQUE_STRING;

		if (request.getParameter("code") != null) {
			String CODE_GENERATED_BY_FACEBOOK = request.getParameter("code");
			String YOUR_REDIRECT_URI2 = "http://www.fiyatineydi.com/FB";
			String YOUR_APP_SECRET = "9c329e2cc15e5924654e21d31f683fef";
			String URL2 = "https://graph.facebook.com/oauth/access_token?client_id="
					+ YOUR_APP_ID
					+ "&redirect_uri="
					+ YOUR_REDIRECT_URI2
					+ "&client_secret="
					+ YOUR_APP_SECRET
					+ "&code="
					+ CODE_GENERATED_BY_FACEBOOK;

			// response.sendRedirect(response.encodeRedirectURL(URL2));

			URL url = new URL(URL2);
			BufferedReader in = new BufferedReader(new InputStreamReader(
					url.openStream()));

			String inputLine;
			String inputLine2 = "";
			String access_token = "";
			while ((inputLine = in.readLine()) != null)
				inputLine2 += inputLine;
			in.close();
			response.getWriter().write("<p>inputLine:" + inputLine2);
			access_token = inputLine2.substring(13,
					inputLine2.indexOf("&expires="));
			response.getWriter().write("<p>access_token:" + access_token);
			/*
			 * String MY_ACCESS_TOKEN = access_token;
			 * 
			 * FacebookClient facebookClient = new DefaultFacebookClient(
			 * MY_ACCESS_TOKEN); FqlUser user = facebookClient.fetchObject("me",
			 * FqlUser.class);
			 * 
			 * response.getWriter().write("<p>User name: " + user.getName());
			 * response.getWriter().write("<p>User id: " + user.getUid());
			 */
			String FQL = "SELECT uid, name, pic_square FROM user WHERE uid = me()";
			//FQL = "SELECT uid, name, pic_square FROM user WHERE uid = me() OR uid IN (SELECT uid2 FROM friend WHERE uid1 = me())";
			//FQL = "select aid, name, owner from album where owner<>me() and owner in(SELECT uid FROM user WHERE uid = me()OR uid IN (SELECT uid2 FROM friend WHERE uid1 = me()))";
			// FQL =
			// "select aid from album where owner<>me() and owner in(SELECT uid FROM user WHERE uid = me()OR uid IN (SELECT uid2 FROM friend WHERE uid1 = me()))";
			// FQL = "SELECT src_big, aid FROM photo WHERE aid in ("+FQL+")";
			/*
			 * FQL=
			 * "SELECT src_big FROM photo WHERE aid in (select aid from album where owner in(SELECT uid FROM user WHERE uid = me() OR uid IN (SELECT uid2 FROM friend WHERE uid1 = me())))"
			 * ; FQL=
			 * "SELECT src_big FROM photo WHERE aid in (select aid from album where owner IN (SELECT uid2 FROM friend WHERE uid1 = me()))"
			 * ;
			 */
			// facebookClient.
			// String FQL = "SELECT name FROM user WHERE uid = 787413422";
			// String FQL = "SELECT name FROM user WHERE uid = me";
			// List<FqlUser> users =
			// facebookClient.executeQuery(FQL,FqlUser.class);
			// FqlUser user = facebookClient.fetchObject("me", FqlUser.class);
			// response.getWriter().write(user.toString());
			// response.getWriter().write(users.get(0).toString());
			/*
			 * 
			 */
			FQL = URLEncoder.encode(FQL);
			String URL3 = "https://graph.facebook.com/fql?q=" + FQL
					+ "&access_token=" + access_token;
			String data = "";
			url = new URL(URL3);
			in = new BufferedReader(new InputStreamReader(url.openStream()));
			while ((inputLine = in.readLine()) != null)
				data = data + inputLine;
			in.close();

			/*
			 * response.getWriter().write("<hr>");
			 * response.getWriter().write(FQL);
			 * response.getWriter().write("<hr>");
			 * response.getWriter().write(URL3);
			 * response.getWriter().write("<hr>");
			 * response.getWriter().write(data);
			 */
			Gson gson = new Gson();
			System.out.println("-----------------------------------------");
			System.out.println(data);
			System.out.println(data.substring(9, data.length()-2));
			System.out.println("-----------------------------------------");
			data=data.substring(9, data.length()-2);
			User u = gson.fromJson(data, User.class);
			System.out.println("name:"+u.getName());
			u.setAccess_token(access_token);

			HttpSession session = request.getSession();
			
			session.setAttribute("user", u);
			System.out.println("#####"+u.getName());
			System.out.println("session Id: " + session.getId() + "<br><br>");
			System.out.println("The SESSION TIMEOUT period is "
		        + session.getMaxInactiveInterval() + " seconds.<br><br>");
			System.out.println("@@@@@"+((User)session.getAttribute("user")).getName());
			DAO.insertUser(u);
			//getServletContext().getRequestDispatcher("/index").forward(request, response);
			response.sendRedirect(response.encodeURL("../index"));
			/*
			 * System.out.println(ds.data.size()); for (Data d : ds.data) { if
			 * (d.getSrc_big() != null) { response.getWriter().write(
			 * "<img src=" + d.getSrc_big() + ">");
			 * response.getWriter().write("<hr>"); } } for (Data d : ds.data) {
			 * if (d.getOwner() != null) { response.getWriter().write(
			 * d.getName() + "(" + d.getOwner() + ")"); FQL =
			 * "SELECT src_big, aid FROM photo WHERE aid =" + d.getAid(); FQL =
			 * URLEncoder.encode(FQL); URL3 =
			 * "https://graph.facebook.com/fql?q=" + FQL + "&access_token=" +
			 * access_token; data = ""; url = new URL(URL3); in = new
			 * BufferedReader(new InputStreamReader( url.openStream())); while
			 * ((inputLine = in.readLine()) != null) data = data + inputLine;
			 * in.close(); Datas ds2 = gson.fromJson(data, Datas.class); for
			 * (Data d2 : ds2.data) { if (d2.getSrc_big() != null) {
			 * response.getWriter().write( "<img src=" + d2.getSrc_big() + ">");
			 * response.getWriter().write("<hr>"); } }
			 * 
			 * response.getWriter().write("<hr>"); }
			 * 
			 * }
			 */
		}
		if (request.getParameter("code") == null) {
			if (request.getParameter("state") == null) {
				response.sendRedirect(response.encodeRedirectURL(URL1));
			}
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	
	}

}
